﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Asxsyd92Core.Utils;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Newtonsoft.Json;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using WebOSCore.Models;

// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace WebOSCore.Controllers.PortalSite
{
    /// <summary>
    /// 注意事项：尽可能不要使用Count()、for循环，请查看Asxsyd92Core.Utils的使用说明
    /// 门户网站控制器
    /// 作者：爱上歆随懿恫
    /// 作者博客：asxsyd92.com
    /// </summary>
    public class PortalSiteController : Controller
    {
        #region+新闻操作
        // GET: /<controller>/
        [Route("api/Article/GetNew")]
        [HttpGet]
        public string GetNew(string title, string type, int page, int limit)
        {
            IEnumerable<object> o = null;
            if (title == null || title == "")
            {
                if (type != null && type != "")
                    o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", page, limit, "Adddate desc", new { Classid = type });
                else
                    o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", page, limit, "Adddate desc");
            }
            else
            {
                if (type != null && type != "")
                    o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", page, limit, "Adddate desc", new { Classid = type, Title = title }, "like");
                else
                    o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", page, limit, "Adddate desc", new { Title = title }, "like");


            }

            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;
        }

        [Route("api/Article/GetRandomNew")]
        [HttpGet]        // [Route("GetNew")]
        public string GetRandomNew(string title, string type, int page, int limit)
        {// 
            IEnumerable<object> o = null;
            if (title == null || title == "")
            {
                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", page, limit, " NEWID()");
            }
            else
            {


                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", page, limit, " NEWID()", new { Title = title }, "like");
            }

            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;

        }
        [HttpGet]
        [Route("api/Article/GetNewDetails")]
        public string GetNewDetails(Guid id)
        {
            var da = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetFromData("A_Article", new { ID = id });
            var os = Models.Unity.ObjModel(da.FirstOrDefault());
            ////更新阅读量
            var vi = os.FirstOrDefault(c => c.Key.ToString() == "views").Value.ToString();
            vi = vi == "" ? "0" : vi;
            os["views"] = Convert.ToInt64(vi) + 1;

            Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.SaveFromData("A_Article", Asxsyd92Core.Utils.JSONhelper.ToJson(os));
            var Nextarticle = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetList("select top 1  *from A_Article where id< '" + id + "'  ORDER BY ID DESC").FirstOrDefault();
            //WebCore.Dal.ArticleDal.Instance.GetList().FirstOrDefault();

            var Lastarticle = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetList("select top 1  *from A_Article where id> '" + id + "'  ORDER BY ID DESC").FirstOrDefault();
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 1, data = os, Nextarticle, Lastarticle });
        }
        [HttpGet]
        [Route("api/ApiData/GetDownload")]
        public string GetDownload(string title,string desc="ID" ,int page=1, int limit=15)
        {
            IEnumerable<object> o = null;
            if (title == null || title == "")
            {
                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("Download", page, limit, desc);
            }
            else
            {


                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("Download", page, limit, desc, new { Title = "%" + title + "%" }, "like");
            }

            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;

        }
        /// <summary>
        /// 填加评论
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("api/Article/AddComment")]
        public string AddComment(string data)
        {
            //修订系统时间
            data = data.Replace("systime", System.DateTime.Now.ToString());
            Guid g = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.SaveFromData("A_Content", data);
            if (g != Guid.Empty)
            {
                return JSONhelper.ToJson(new { code = 0, msg = "留言成功", Success = true }, false);

            }

            return JSONhelper.ToJson(new { code = 0, msg = "留言失败", Success = false }, false);
        }
        #endregion
        [HttpGet]
        [Route("api/taobao/TaoBaosoAds")]
        public string TaoBaosoAds(string title, int page = 1, int limit = 15)
        {
            IEnumerable<object> o = null;
            o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("T_Map_dataItem", page, limit, " NEWID()");
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 15, data = o });

        }
        [HttpGet]
        [Route("api/Article/GetTencentVideoList")]
        public string GetTencentVideoList(string title, int page, int limit)
        {
            IEnumerable<object> o = null;
            o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("TencentVideo", page, limit, "ID");
            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;
        }
        [HttpGet]
        [Route("api/taobao/TaoBaoSearch")]
        public async Task<string> TaoBaoSearch(string title = "", int page = 1, int limit = 15)
        {
            IEnumerable<object> o = null;
            if (title == null || title == "")
            {
                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("T_Map_dataItem", page, limit, " datatime desc");

                if (o.FirstOrDefault() != null)
                {

                    var os = Models.Unity.ObjModel(o.FirstOrDefault());
                    return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
                }
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;
            }
            var OS = TaoBaoSearchAsync(title, page, limit);
            var jsonData = LitJSONCore.JsonMapper.ToObject(OS);
            var data = jsonData["tbk_dg_material_optional_response"];
            var da = data["total_results"];
            var das = data["result_list"];
            var jsonModel = JsonConvert.DeserializeObject<List<Models.Map_dataItem>>(das["map_data"].ToJson());
            try
            {
                await Task.Run(() => TobaoAdd(jsonModel));

                var daqs = Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = da.ToString(), data = jsonModel.ToList() });
                return daqs;//Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = da, data = jsonModel.ToList() }); ;
            }
            catch (Exception ex)
            {
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = da, data = "" }); ;

            }


        }

        private async void TobaoAdd(List<Map_dataItem> jsonModel)
        {
            foreach (var id in jsonModel)
            {
                var da = GetMapByID(id.num_iid);
                if (!da)
                {
                    id.datatime = System.DateTime.Now;
                    var json = Asxsyd92Core.Utils.JSONhelper.ToJson(id);
                    await Task.Run(() => Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.SaveFromData("T_Map_dataItem", json));
                }

            }
        }

        private bool GetMapByID(string num_iid)
        {
            string sql = "SELECT * FROM T_Map_dataItem where num_iid = '" + num_iid + "'";
            var da = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("T_Map_dataItem", 1, 1, "ID", new { num_iid = num_iid }).FirstOrDefault() as Dictionary<object, object>;
            //  var da = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetList(sql).FirstOrDefault() as Dictionary<object,object>;
            if (da != null) { return true; };
            return false;
        }
        public string TaoBaoSearchAsync(string title = "", long page = 1, long limit = 15)
        {
            ITopClient client = new DefaultTopClient(Models.Config.appUrl, Models.Config.appKey, Models.Config.appSecret, "json");
            TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
            req.PageNo = page;
            req.PageSize = limit;
            req.Q = title;
            req.AdzoneId = 71272250295L;

            TbkDgMaterialOptionalResponse rsp = client.Execute(req);
            return rsp.Body;
            //var jsonModel = JsonConvert.DeserializeObject<object>(rsp.Body);
            //return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 8, data = jsonModel });


            //  return JSONhelper.ToJson(new { code = 0, msg = "", count = jsonModel.tbk_dg_material_optional_response.total_results, data = jsonModel.tbk_dg_material_optional_response.result_list.map_data });

        }
        [HttpGet]
        [Produces("application/json")]
        [Route("News/NewsDetail")]
        public IActionResult NewsDetail(Guid id)

        {

            var contentResult = new ContentResult
            {
                Content = StringHTML("A_Article", id),
                ContentType = "text/html; charset=utf-8",
                StatusCode = 200

            };

            return contentResult;
        }
        [HttpGet]
        [Produces("application/json")]
        [Route("PortalSite/DownDetail")]
        public IActionResult DownDetail(Guid id)

        {

            var contentResult = new ContentResult
            {
                Content = StringHTML("Download", id),
                ContentType = "text/html; charset=utf-8",
                StatusCode = 200

            };

            return contentResult;
        }
        public string StringHTML(string table,Guid id)
        {
            var da = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetFromData(table, new { ID = id });
            var os = Models.Unity.ObjModel(da.FirstOrDefault());
            ////更新阅读量
            os["views"] = Convert.ToInt64(os.FirstOrDefault(c => c.Key.ToString() == "views").Value.ToString()) + 1;

            Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.SaveFromData(table, Asxsyd92Core.Utils.JSONhelper.ToJson(os));
            var Nextarticle = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetList("select top 1  *from "+ table + " where id< '" + id + "'  ORDER BY ID DESC").FirstOrDefault();
            //WebCore.Dal.ArticleDal.Instance.GetList().FirstOrDefault();

            var Lastarticle = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetList("select top 1  *from " + table + " where id> '" + id + "'  ORDER BY ID DESC").FirstOrDefault();
            var html = "";
            if (table == "Download")
            {
                 html = WriteFile(os, Nextarticle as Dictionary<object, object>, Lastarticle as Dictionary<object, object>);

            }
            else {
                html = WriteFiles(os, Nextarticle as Dictionary<object, object>, Lastarticle as Dictionary<object, object>);

            }
            return html;
        }
        public static string WriteFiles(Dictionary<Object, Object> torrent, Dictionary<Object, Object> Nextarticle, Dictionary<Object, Object> Lastarticle)
        {

            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/PortalSite/newsemplate.html";
            Encoding code = Encoding.GetEncoding("utf-8");
            // 读取模板文件
            // string temp = HttpContext.Current.Server.MapPath("Text.htm");
            StreamReader sr = null;
            string str = "";
            try
            {
                sr = new StreamReader(path, code);
                str = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                //sr.Close();
                return exp.Message; ;

            }

            // 替换内容
            // 这时,模板文件已经读入到名称为str的变量中了
            if (torrent == null)
            {

            }
            else
            {

                var sj = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("A_Article", 1, 10, " NEWID()");
                if (sj.FirstOrDefault() != null)
                {
                    var htmls = "";
                    //   var llll = sj.ToList() as IEnumerable<Dictionary<object, object>>;
                    var lslsl = sj.ToList() as IEnumerable<object>;
                    foreach (var ite in lslsl.ToList())
                    {
                        var item = ite as Dictionary<object, object>;
                        if (item.FirstOrDefault().Key != null)
                        {
                            htmls += "<li ><span class='layui-badge'>荐</span><a href='/News/NewsDetail?id=" + item.FirstOrDefault(c => c.Key.ToString() == "ID").Value.ToString() + "'>" + item.FirstOrDefault(c => c.Key.ToString() == "Title").Value.ToString() + "</a> </li>";

                        }
                    }
                    str = str.Replace("$sj$", htmls);
                }
                else { str = str.Replace("$sj$", ""); }
                str = str.Replace("$Title$", torrent["Title"] == null ? "" : torrent["Title"].ToString());
                str = str.Replace("$ID$", torrent == null ? "" : torrent["ID"].ToString());
                str = str.Replace("$Description$", torrent["Description"].ToString()); //模板页中的ShowArticle
                str = str.Replace("$Adddate$", torrent["Adddate"].ToString());
                str = str.Replace("$views$", torrent["views"].ToString());
                str = str.Replace("$Contents$", torrent["Contents"].ToString());
                str = str.Replace("$Author$", torrent["Author"].ToString());
                str = str.Replace("$Nextarticle.ID$", Nextarticle == null ? "" : Nextarticle["ID"].ToString());
                str = str.Replace("$Lastarticle.ID$", Lastarticle == null ? "" : Lastarticle["ID"].ToString());
                str = str.Replace("$Lastarticle.Title$", Lastarticle == null ? "" : Lastarticle["Title"].ToString());
                str = str.Replace("$Nextarticle.Title$", Nextarticle == null ? "" : Nextarticle["Title"].ToString());
                str = str.Replace("$Nextarticle.views$", Nextarticle == null ? "" : Nextarticle["views"].ToString());
                str = str.Replace("$Lastarticle.views$", Lastarticle == null ? "" : Lastarticle["views"].ToString());
            }

            try
            {
                return str;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                // sw.Close();
            }
        }
        public static string WriteFile(Dictionary<Object, Object> torrent, Dictionary<Object, Object> Nextarticle, Dictionary<Object, Object> Lastarticle)
        {

            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/PortalSite/downdetail.html";
            Encoding code = Encoding.GetEncoding("utf-8");
            // 读取模板文件
            // string temp = HttpContext.Current.Server.MapPath("Text.htm");
            StreamReader sr = null;
            string str = "";
            try
            {
                sr = new StreamReader(path, code);
                str = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                //sr.Close();
                return exp.Message; ;

            }

            // 替换内容
            // 这时,模板文件已经读入到名称为str的变量中了
            if (torrent == null)
            {

            }
            else
            {

                var sj = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage("Download", 1, 10, " NEWID()");
                if (sj.FirstOrDefault() != null)
                {
                    var htmls = "";
                    //   var llll = sj.ToList() as IEnumerable<Dictionary<object, object>>;
                    var lslsl = sj.ToList() as IEnumerable<object>;
                    foreach (var ite in lslsl.ToList())
                    {
                        var item = ite as Dictionary<object, object>;
                        if (item.FirstOrDefault().Key != null)
                        {
                            htmls += "<li ><span class='layui-badge'>荐</span><a href='/PortalSite/DownDetail?id=" + item.FirstOrDefault(c => c.Key.ToString() == "ID").Value.ToString() + "'>" + item.FirstOrDefault(c => c.Key.ToString() == "Title").Value.ToString() + "</a> </li>";

                        }
                    }
                    str = str.Replace("$sj$", htmls);
                }
                else { str = str.Replace("$sj$", ""); }
                str = str.Replace("$Title$", torrent["Title"] == null ? "" : torrent["Title"].ToString());
                str = str.Replace("$ID$", torrent == null ? "" : torrent["ID"].ToString());
                str = str.Replace("$Description$", torrent["Description"].ToString()); //模板页中的ShowArticle
                str = str.Replace("$Adddate$", torrent["Adddate"].ToString());
                str = str.Replace("$views$", torrent["views"].ToString());
                str = str.Replace("$Url$", torrent["Url"].ToString());
                str = str.Replace("$Author$", torrent["Author"].ToString());
                str = str.Replace("$Nextarticle.ID$", Nextarticle == null ? "" : Nextarticle["ID"].ToString());
                str = str.Replace("$Lastarticle.ID$", Lastarticle == null ? "" : Lastarticle["ID"].ToString());
                str = str.Replace("$Lastarticle.Title$", Lastarticle == null ? "" : Lastarticle["Title"].ToString());
                str = str.Replace("$Nextarticle.Title$", Nextarticle == null ? "" : Nextarticle["Title"].ToString());
                str = str.Replace("$Nextarticle.views$", Nextarticle == null ? "" : Nextarticle["views"].ToString());
                str = str.Replace("$Lastarticle.views$", Lastarticle == null ? "" : Lastarticle["views"].ToString());
            }

            try
            {
                return str;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            finally
            {
                // sw.Close();
            }
        }
        [HttpGet]
        [Produces("application/json")]
        [Route("api/File/download")]
        public IActionResult download(string url)
        {
            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            var stream = System.IO.File.OpenRead(m_localPath + "wwwroot" + url);
            Encoding code = Encoding.GetEncoding("utf-8");
            // 读取模板文件
            // string temp = HttpContext.Current.Server.MapPath("Text.htm");
            StreamReader sr = null;
            string str = "";
            try
            {
                sr = new StreamReader(m_localPath + "wwwroot" + url, code);
                str = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                //sr.Close();
                //return exp.Message; ;
            }
            var contentResult = new ContentResult
            {
                Content = str,
                ContentType = "text/html; charset=utf-8",
                StatusCode = 200

            };

            return contentResult;

        }
        /// <summary>
        /// 统一状态均为Status
        /// </summary>
        /// <param name="tab"></param>
        /// <param name="title"></param>
        /// <param name="desc"></param>
        /// <param name="Status"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("api/ApiData/GetCommonListByID")]
        public string GetCommonListByID(string tab, Guid ID, string title, string desc = "ID", int Status = 1, int page = 1, int limit = 15)
        {
            IEnumerable<object> o = null;
            if (tab == null || tab == "")
            {
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;

            }

            if (title == null || title == "")
            {
                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage(tab, page, limit, desc, new { Status = Status, ArtID = ID });
            }
            else
            {


                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage(tab, page, limit, desc, new { Name = "%" + title + "%", Status = Status, ArtID = ID }, "like");
            }

            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;

        }
        [HttpGet]
        [Route("api/ApiData/GetCommonList")]
        public string GetCommonList(string tab, string title, string desc = "ID", int Status = 1, int page = 1, int limit = 15)
        {
            IEnumerable<object> o = null;
            if (tab == null || tab == "")
            {
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;

            }

            if (title == null || title == "")
            {
                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage(tab, page, limit, desc, new { Status = Status });
            }
            else
            {


                o = Asxsyd92Core.Utils.Data.SQLServer.SqlFromData.GetPage(tab, page, limit, desc, new { Name = "%" + title + "%", Status = Status }, "like");
            }

            if (o.FirstOrDefault() != null)
            {

                var os = Models.Unity.ObjModel(o.FirstOrDefault());
                return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = os.FirstOrDefault(c => c.Key.ToString() == "Count").Value, data = o });
            }
            return Asxsyd92Core.Utils.JSONhelper.ToJson(new { code = 0, msg = "", count = 0, data = o }); ;

        }
        [Route("api/ApiData/GetByCode")]
        [HttpGet]
        public string GetByCode(string code, string tab)
        {

            return WebOS.Bll.DictionaryBll.Instance.GetByCode(code);

        }

        [HttpGet]
        [Route("api/Baidu/BaiduXML")]
        public string BaiduXML(string data,int type=0)
        {
            string info = "";
            if (type == 0)
            {
                List<string> array = new List<string>();
                string url = "http://asxsyd92.com/news/newsdetail?id=" + data;
                array.Add(url);
                 info = HttpHelper.BaiduPostUpdateUrl("http://data.zz.baidu.com/urls?site=asxsyd92.com&token=t25j9iZIkCHaA2eg", array.ToArray());
                string mailTo = "爱上歆随懿恫<asxsyd92@foxmail.com>";  //接收方
                string mailSubject = "百度推送提醒";      //邮件主题   
                string mailContent = "<html><body><div><font color='blue'>已有一条文章被用户推送至百度站长平台</font>  <a href='http://asxsyd92.com/webos.html'>点击查看详情</a></div></body></html>";  //邮件内容
                try
                {
                    Asxsyd92Core.Utils.HttpHelper.SendEmail(mailTo, mailSubject, mailContent);
                }
                catch { }
            }
            else {
                List<string> array = new List<string>();
                string url = "http://asxsyd92.com/PortalSite/DownDetail?id=" + data;
                array.Add(url);
                info = HttpHelper.BaiduPostUpdateUrl("http://data.zz.baidu.com/urls?site=asxsyd92.com&token=t25j9iZIkCHaA2eg", array.ToArray());
                string mailTo = "爱上歆随懿恫<asxsyd92@foxmail.com>";  //接收方
                string mailSubject = "百度推送提醒";      //邮件主题   
                string mailContent = "<html><body><div><font color='blue'>已有一条文章被用户推送至百度站长平台</font>  <a href='http://asxsyd92.com/webos.html'>点击查看详情</a></div></body></html>";  //邮件内容
                try
                {
                    Asxsyd92Core.Utils.HttpHelper.SendEmail(mailTo, mailSubject, mailContent);
                }
                catch { }
            }
         
         
            return info;
        }
        /// <summary>
        /// 生成地图
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("PortalSite/WriteMap")]
        public  string WriteMap(string  data)
        {
            try
            {
                string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
                string path = m_localPath + "wwwroot\\map.xml";
                Encoding code = Encoding.GetEncoding("utf-8");
                StreamReader sr = null;


                string str = "";
                try
                {
                    sr = new StreamReader(path, code);
                    str = sr.ReadToEnd(); // 读取文件

                }
                catch (Exception exp)
                {
                    //sr.Close();
                    return exp.Message; ;

                }
                var info = "";
                List<string> array = new List<string>();
                var xml = "";
              var da=  data.Split(',');
                foreach (var itme in da)
                {
                    string url = "http://asxsyd92.com/news/newsdetail?id=" + itme.ToString();
                    array.Add(url);
                    xml += string.Format(" <url><loc>{0}</loc> <lastmod>{1}</lastmod> <changefreq>daily</changefreq><priority>0.8</priority></url>", url, System.DateTime.Now.ToString("yyyy-MM-dd"));

                }
                try
                {
                    //生成地图
                    str = str.Replace("$map$", xml);
                    string m_localPathx = AppDomain.CurrentDomain.BaseDirectory;
                    string pathx = m_localPath + "wwwroot\\Sitemap.xml";
                    //把txt清空
                    FileStream stream = System.IO.File.Open(pathx, FileMode.OpenOrCreate, FileAccess.Write);
                    stream.Seek(0, SeekOrigin.Begin);
                    stream.SetLength(0);
                    stream.Close();
                    //向txt里面追加信息
                    StreamWriter sww = new StreamWriter(pathx, true, code);
                    sww.Write(str);
                    sww.Flush();
                    sww.Close();
     
                    //向百度推送
                }
                catch (Exception ex)
                {
                    return ex.Message;
                }

                return "map生成成功！";
            }
            catch (Exception EX)
            {
                return EX.Message;
            }
        }

        [HttpGet]
        [Produces("application/json")]
        [Route("qqlogin")]
        public IActionResult qqlogin()

        {

            string m_localPath = AppDomain.CurrentDomain.BaseDirectory;
            string path = m_localPath + "wwwroot/qqlogin.html";
            Encoding code = Encoding.GetEncoding("utf-8");
            // 读取模板文件
            // string temp = HttpContext.Current.Server.MapPath("Text.htm");
            StreamReader sr = null;
            string str = "";
            try
            {
                sr = new StreamReader(path, code);
                str = sr.ReadToEnd(); // 读取文件
                sr.Close();
            }
            catch(Exception ex) { str = ex.Message; }
            var contentResult = new ContentResult
            {
                Content = str,
                ContentType = "text/html; charset=utf-8",
                StatusCode = 200

            };

            return contentResult;
        }
    }
}